//
//  MYFactoryManager.m
//  GoHiking_app
//
//  Created by qf on 15/10/13.
//  Copyright (c) 2015年 qf. All rights reserved.
//

#import "MYFactoryManager.h"
#import "CommonDefines.h"

@implementation MYFactoryManager

#pragma mark -- 计算高度
+ (CGFloat)heightForString:(NSString *)string fontSize:(CGFloat)fontSize andWidth:(CGFloat)width{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil];
    return rect.size.height;
}

+ (CGFloat)widthForString:(NSString *)string fontSize:(CGFloat)fontSize andHeight:(CGFloat)height{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil];
    
    return rect.size.width;
}

#pragma mark -- 时间
+ (NSString *)getStartTimeDate:(double)dateTime format:(NSString *)format{
    if (format == nil) {
        format = @"yyyy/MM/dd";
    }
    NSTimeInterval time= dateTime;//因为时差问题要加8小时 == 28800 sec
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式 @"yyyy/MM/dd"
    [dateFormatter setDateFormat:format];
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return currentDateStr;
}
/*处理返回应该显示的时间*/
+ (NSString *) returnUploadTime:(NSString *)timeStr
{
    NSTimeInterval time= [timeStr doubleValue];//因为时差问题要加8小时 == 28800 sec
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    NSDate *datenow = [NSDate date];
    NSDateFormatter * dm = [[NSDateFormatter alloc]init];
    //指定输出的格式   这里格式必须是和上面定义字符串的格式相同，否则输出空
    [dm setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate * newdate = [dm dateFromString:currentDateStr];
    long dd = (long)[datenow timeIntervalSince1970] - [newdate timeIntervalSince1970];
    NSString *timeString=@"";
    if (dd/3600<1)
    {
        timeString = [NSString stringWithFormat:@"%ld", dd/60];
        timeString=[NSString stringWithFormat:@"%@分钟前", timeString];
    }
    if (dd/3600>1&&dd/86400<1)
    {
        timeString = [NSString stringWithFormat:@"%ld", dd/3600];
        timeString=[NSString stringWithFormat:@"%@小时前", timeString];
    }
    if (dd/86400>1)
    {
        timeString = [NSString stringWithFormat:@"%ld", dd/86400];
        timeString=[NSString stringWithFormat:@"%@天前", timeString];
    }
    return timeString;
}
//返回时间戳
+ (NSString *)returnTimestamp:(NSString *)timeStr{
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:timeStr];
    NSTimeInterval timeSp = [date timeIntervalSince1970];
    return [NSString stringWithFormat:@"%f",timeSp];
}

#pragma mark 字符与字典的转换
//字符串转字典与字典转字符串
+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil];
    return responseJSON;
}
+ (NSArray *)parseJSONStringToNSArray:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil];
    return responseJSON;
}
+ (NSString*)arrayToJson:(NSArray *)arr

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

//判断对象是否为空
+ (NSString *)returnRealValue:(id)sendValue {
    if ([sendValue isKindOfClass:[NSNull class]] || sendValue == NULL) {
        return @"";
    }
    if ([sendValue isKindOfClass:[NSNumber class]]) {
        return [sendValue stringValue];
    }
    return sendValue;
}

#pragma 各种格式检验
//获取部分显示手机格式
+ (NSString *)getPhoneText:(NSString *)phoneNum {
    if ([phoneNum isKindOfClass:[NSString class]]) {
        if (phoneNum.length > 10) {
            NSString *backStr = [phoneNum substringFromIndex:7];//截取掉下标6之后的字符串
            
            return [NSString stringWithFormat:@"*******%@",backStr];
        }
    }
    return @"****";
}
//手机格式
+ (BOOL)phoneNum:(NSString *) textString {
    NSString *number = @"^[0-9]{8,}$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}
//大陆手机格式+86
+ (BOOL)CHPhoneNum:(NSString *)textString{
    NSString *number = @"^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}
//香港手机格式+852
+ (BOOL)HKPhoneNum:(NSString *)textString{
    NSString *number = @"^(5|6|8|9)\\d{7}$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}
//数字检验
+ (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@".0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}
//判断输入的是否是表情
+(BOOL)isContainsEmoji:(NSString *)string {
    
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         
         // surrogate pair
         
         if (0xd800 <= hs && hs <= 0xdbff) {
             
             if (substring.length > 1) {
                 
                 const unichar ls = [substring characterAtIndex:1];
                 
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     
                     isEomji = YES;
                     
                 }
                 
             }
             
         } else if (substring.length > 1) {
             
             const unichar ls = [substring characterAtIndex:1];
             
             if (ls == 0x20e3) {
                 
                 isEomji = YES;
                 
             }
         } else {
             // non surrogate
             
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
     }];
    return isEomji;
    
}
//身份证号
+ (BOOL) validateIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}
+ (BOOL)ConformToTheMoneyInputString:(NSString *)string shouldChangeCharactersInRange:(NSRange)range currtentTextField:(UITextField *)textField{
    BOOL isHavePoint = NO;
    if ([textField.text rangeOfString:@"."].location == NSNotFound) {
        isHavePoint = NO;
    }else{
        isHavePoint = YES;
    }
    if ([string length] > 0) {
        if ([string length] != 1) {
            return NO;
        }
        unichar single = [string characterAtIndex:0];//当前输入的字符
        if ((single >= '0' && single <= '9') || single == '.') {//数据格式正确
            //首字母不能为0和小数点
            if([textField.text length] == 0){
                if(single == '.') {
                    return NO;
                }
                //                if (single == '0') {
                //                    return NO;
                //                }
            }
            //输入的字符是否是小数点
            if (single == '.') {
                if(!isHavePoint)//text中还没有小数点
                {
                    isHavePoint = YES;
                    return YES;
                    
                }else{
                    return NO;
                }
            }else{
                if (isHavePoint) {//存在小数点
                    //判断小数点的位数
                    NSRange ran = [textField.text rangeOfString:@"."];
                    if (range.location - ran.location <= 2) {
                        return YES;
                    }else{
                        return NO;
                    }
                }else{
                    return YES;
                }
            }
        }else{//输入的数据格式不正确
            return NO;
        }
    }
    return YES;
    
}


#pragma 缓存文件处理
+ (float)getCacheSize{
    // 获取Caches目录路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES);
    NSString *cachesDir = [paths objectAtIndex:0];
    
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:cachesDir]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:cachesDir] objectEnumerator];//从前向后枚举器
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSLog(@"fileName ==== %@",fileName);
        NSString* fileAbsolutePath = [cachesDir stringByAppendingPathComponent:fileName];
        NSLog(@"fileAbsolutePath ==== %@",fileAbsolutePath);
        CGFloat size = 0;
        NSFileManager* manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:fileAbsolutePath]){
            size = [[manager attributesOfItemAtPath:fileAbsolutePath error:nil] fileSize];
        }
        folderSize += size;
    }
    NSLog(@"folderSize ==== %lld",folderSize);
    return folderSize/(1024.0*1024.0);
}
+ (void)clearCache{
    // 获取Caches目录路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES);
    NSString *cachesDir = [paths objectAtIndex:0];
    //清除缓存
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:cachesDir]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:cachesDir];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[cachesDir stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
}

#pragma 登录页的快速跳转
//调到登录页
//+ (BOOL)pushVCToLoginController:(UIViewController *)selfVC  withTableView:(BaseTableView *)tableView{
//    NSString *token = [UserDefaults objectForKey:@"tokenContent"];
//    NSLog(@"token ------- %@",token);
//    if (token == NULL || token.length == 0) {
//        if (tableView != nil) {
//            [tableView.mj_header endRefreshing];
//            [tableView.mj_footer endRefreshing];
//        }
//
//        /*
//
//
//         //此处做跳转处理
//
//
//         */
//
//        double delayInSeconds = 1.0;
//        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
//        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
////            [selfVC.navigationController pushViewController:loginVC animated:YES];
//        });
//
//        return YES;
//    }
//    return NO;
//}

//调到登录页
+ (BOOL)quickPushVCToLoginController:(UIViewController *)selfVC {
    //    NSString *token = [UserDefaults objectForKey:@"tokenContent"];
    //    NSLog(@"token ------- %@",token);
    //    if (token == NULL || token.length == 0) {
    
    /*
     
     
     //此处做跳转处理
     
     
     */
    
    return YES;
    //    }
    //    return NO;
}

//判断系统版本
+(int)osVersion
{
    //使用UIDevice设别类获取版本, 名字.....
    return [[[UIDevice currentDevice] systemVersion] intValue];
}

// 设置本地通知
+ (void)registerLocalNotification:(NSDate*)alertDate alertBody:(NSString *)alertBody userDict:(NSDictionary *)userDict
{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置触发通知的时间
    NSDate *fireDate = alertDate;
    NSLog(@"data :%@",fireDate);
    notification.fireDate = fireDate;
    // 时区
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 设置重复的间隔
    notification.repeatInterval = kCFCalendarUnitSecond;
    
    // 通知内容
    notification.alertBody = alertBody;
    notification.applicationIconBadgeNumber = 1;
    // 通知被触发时播放的声音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知参数
    notification.userInfo = userDict;
    
    // ios8后，需要添加这个注册，才能得到授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    }
    else
    {
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    }
    
    // 执行通知注册
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

// 取消某个本地推送通知
+ (void)cancelLocalNotificationWithKey:(NSString *)key
{
    // 获取所有本地通知数组
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    
    for (UILocalNotification *notification in localNotifications)
    {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo)
        {
            // 根据设置通知参数时指定的key来获取通知参数
            NSString *info = userInfo[key];
            
            // 如果找到需要取消的通知，则取消
            if (info != nil)
            {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                break;
            }
        }
    }
}

//数字返回 大于万时返回xxxx万
+ (NSString *)returnTenThousand:(NSInteger)num {
    NSString *str;
    if (num >= 10000) {
        if (num%10000 < 500) {
            str = [NSString stringWithFormat:@"%.0f万",num/10000.0];
        }else {
            str = [NSString stringWithFormat:@"%.1f万",num/10000.0];
        }
    }else {
        str = [NSString stringWithFormat:@"%d", (int)num];
    }
    return str;
}
//数字返回 大于100时返回99+
+ (NSString *)returnHundred:(NSInteger)num {
    NSString *str;
    if (num >= 100) {
        str = @"99+";
    }else {
        str = [NSString stringWithFormat:@"%d", (int)num];
    }
    return str;
}

+ (int)convertToInt:(NSString *)strtemp maxLength:(int)maxLen//判断中英混合的的字符串长度
{
    int strlength = 0;
    for (int i=0; i< [strtemp length]; i++) {
        int a = [strtemp characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff) { //判断是否为中文
            strlength += 2;
        }else {
            strlength += 1;
        }
        if (strlength >= maxLen*2) {
            return i;
        }
    }
    return (int)strtemp.length;
}
//添加文字阴影
+ (NSMutableAttributedString *)shadowString:(NSString *)str {
    NSShadow *shadow = [[NSShadow alloc]init];
    //    shadow.shadowBlurRadius = 1.0;
    shadow.shadowOffset = CGSizeMake(4/3*plusLayoutScale, 0);
    shadow.shadowColor = color(0, 0, 0, 0.75);
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str attributes:nil];
    [attributedString addAttribute:NSShadowAttributeName
                             value:shadow
                             range:NSMakeRange(0, attributedString.length)];
    return attributedString;
}
//加文字阴影自定义
+ (NSMutableAttributedString *)shadowString:(NSString *)str shadowOffset:(CGSize)offset shadowColor:(UIColor *)color{
    NSShadow *shadow = [[NSShadow alloc]init];
    //    shadow.shadowBlurRadius = 1.0;
    shadow.shadowOffset = CGSizeEqualToSize(CGSizeZero, offset)?CGSizeMake(4/3*plusLayoutScale, 0):offset;
    shadow.shadowColor = color?color:color(0, 0, 0, 0.75);
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str attributes:nil];
    [attributedString addAttribute:NSShadowAttributeName
                             value:shadow
                             range:NSMakeRange(0, attributedString.length)];
    return attributedString;
}

+ (CAGradientLayer *)setGradualChangingColor:(UIView *)view fromColor:(UIColor *)fromColor toColor:(UIColor *)toColor{
    //    CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角)
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.bounds;
    //  创建渐变色数组，需要转换为CGColor颜色
    gradientLayer.colors = @[(__bridge id)fromColor.CGColor,(__bridge id)toColor.CGColor];
    //  设置渐变颜色方向，左上点为(0,0), 右下点为(1,1)
    gradientLayer.startPoint = CGPointMake(0.5, 0);
    gradientLayer.endPoint = CGPointMake(0.5, 1);
    //  设置颜色变化点，取值范围 0.0~1.0
    gradientLayer.locations = @[@0,@1];
    
    return gradientLayer;
}


// 自适应尺寸大小
+ (NSString *)webImageFitToDeviceSize:(NSString *)str
{
    
    if (str == nil) {
        return @"";
    }
    str = [NSString stringWithFormat:@"<body><div class=\"home\"><div style=\"font-size: 0;\"><p>%@</p></div></div></body>", str];
    NSMutableString *strContent = [NSMutableString string];
    [strContent appendString:@"<!DOCTYPE HTML>"];
    [strContent appendString:@"<html>"];
    [strContent appendString:@"<head>"];
    [strContent appendString:@"<meta charset=\"utf-8\">"];
    [strContent appendString:@"<meta id=\"viewport\" name=\"viewport\" content=\"width=device-width*0.9,initial-scale=1.0,maximum-scale=1.0,user-scalable=false\" />"];
    [strContent appendString:@"<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />"];
    [strContent appendString:@"<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />"];
    [strContent appendString:@"<meta name=\"black\" name=\"apple-mobile-web-app-status-bar-style\" />"];
    [strContent appendString:@"<style>body{font-size: 16px;overflow:hidden;width:100%;}</style>"];
    [strContent appendString:@"<style>img{width:auto;max-width:100%;display:block;margin:5px auto 5px;}</style>"];
    [strContent appendString:@"<style>p{font-size:16px;word-wrap:break-word;}</style>"];
    [strContent appendString:@"<style>div{font-size:16px;}</style>"];
    [strContent appendString:@"<style>span{font-size:16px;}</style>"];
    [strContent appendString:@"<style>.home{width:94%;position:absolute;left:3%;top:0;}</style>"];
    [strContent appendString:@"<style>img{align-content: center;}</style>"];
    [strContent appendString:@"<style>iframe{width:100%;}</style>"];
    [strContent appendString:@"<style>embed{width:100%;}</style>"];
    
    [strContent appendString:[NSString stringWithFormat:@"%@",str]];
    
    return strContent;
}

+(NSMutableAttributedString*)subStr:(NSString *)string
{
    NSError *error;
    //可以识别url的正则表达式
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    //NSString *subStr;
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    NSArray *rangeArr=[[NSMutableArray alloc]init];
    
    for (NSTextCheckingResult *match in arrayOfAllMatches)
    {
        NSString* substringForMatch;
        substringForMatch = [string substringWithRange:match.range];
        [arr addObject:substringForMatch];
        
    }
    NSString *subStr=string;
    for (NSString *str in arr)
    {
        subStr=[subStr  stringByReplacingOccurrencesOfString:str withString:@"网页链接"];
    }
    rangeArr=[self rangesOfString:@"网页链接" inString:subStr];
    
    //    //计算大小
    UIFont *font = [UIFont systemFontOfSize:15];
    NSMutableAttributedString *attributedText;
    
    attributedText=[[NSMutableAttributedString alloc]initWithString:subStr attributes:@{NSFontAttributeName :font}];
    
    for(NSValue *value in rangeArr)
    {
        NSInteger index=[rangeArr indexOfObject:value];
        NSRange range=[value rangeValue];
        [attributedText addAttribute: NSLinkAttributeName value: [NSURL URLWithString:[NSString stringWithFormat:@"%@",[arr objectAtIndex:index]]] range:range];
    }
    return attributedText;
    
    
}
//获取查找字符串在母串中的NSRange
+ (NSArray *)rangesOfString:(NSString *)searchString inString:(NSString *)str {
    
    NSMutableArray *results = [NSMutableArray array];
    
    NSRange searchRange = NSMakeRange(0, [str length]);
    
    NSRange range;
    
    while ((range = [str rangeOfString:searchString options:0 range:searchRange]).location != NSNotFound) {
        
        [results addObject:[NSValue valueWithRange:range]];
        
        searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range));
        
    }
    
    return results;
}
+ (NSString *)formatFloat:(float)f
{
    NSString *str = [NSString stringWithFormat:@"%.2f",f];
    f = [str floatValue];
    if (fmodf(f, 1)==0) {//如果有一位小数点
        return [NSString stringWithFormat:@"%.0f",f];
    } else if (fmodf(f*10, 1)==0) {//如果有两位小数点
        return [NSString stringWithFormat:@"%.1f",f];
    } else {
        return [NSString stringWithFormat:@"%.2f",f];
    }
}

@end
